package com.daguchuangyi.erp_android.manager;

import android.text.TextUtils;

import com.daguchuangyi.erp_android.util.IPCheckUtil;
import com.daguchuangyi.erp_android.util.PreferenceUtil;
import com.jude.utils.JUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

//import com.facebook.stetho.okhttp3.StethoInterceptor;

/**
 * Created by lijianjian on 2018/3/17.
 */

public class NetworkManager {
    private String mBaseUrl = "";

    private static NetworkManager sInstance;
    private Retrofit mRetrofit;

    public NetworkManager() {

        String ipSaved = PreferenceUtil.getString(PreferenceUtil.TAG_IP_SAVED, "139.224.16.98");
        String baseUrl = "http://" + ipSaved + ":3000";
        initRetrofit(baseUrl);
    }

    public void refreshBaseUrl(String baseUrl) {
        String urlPath = "";
//        Pattern ipPattern = Pattern.compile(PATTERN_IP);
//        Matcher matcher = ipPattern.matcher(baseUrl);
//        if (matcher.find()) {
        if (IPCheckUtil.isValidIp(baseUrl)) {
            JUtils.Log("matchIp address:" + baseUrl);
            urlPath = "http://" + baseUrl.trim() + ":3000";
        } else {
            JUtils.Log("match URL address:" + baseUrl);
            if (!baseUrl.startsWith("http")) {
                urlPath = "http://" + baseUrl.trim() + ":3000";
            } else {
                urlPath = baseUrl;
            }
            JUtils.Log("match ");
        }
        initRetrofit(urlPath);
    }

    private void initRetrofit(String baseUrl) {
        mBaseUrl = baseUrl;
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .retryOnConnectionFailure(true)
//                .addNetworkInterceptor(new StethoInterceptor())
                .readTimeout(5, TimeUnit.MINUTES)
                .writeTimeout(5, TimeUnit.MINUTES)
                .connectTimeout(5, TimeUnit.MINUTES)
                .addNetworkInterceptor(chain -> {
                    String token = UserInfoManager.getUserInfoManager().getToken();
                    Request originalRequest = chain.request();
                    if (TextUtils.isEmpty(token)) {
                        return chain.proceed(originalRequest);
                    }

                    Request authorised = originalRequest.newBuilder()
                            .addHeader("Authorization", token)
                            .addHeader("Client-Type", "Android")
                            .addHeader("x-mobile", "Android")
                            .build();
                    return chain.proceed(authorised);
                })
                .build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public String getBaseUrl() {
        return mBaseUrl;
    }

    public Retrofit getRetrofit() {
        return mRetrofit;
    }

    public static synchronized NetworkManager getInstance() {
        if (sInstance == null) {
            synchronized (NetworkManager.class) {
                sInstance = new NetworkManager();
            }
        }
        return sInstance;
    }
}
